#include "Continents.h"

#include <QApplication>
#include <QDir>
#include <QDebug>

Continents* getContinents()
{
    static Continents t;
    return &t;
}

Continents::Continents()
{
    QString path = QApplication::applicationDirPath () + "/Ress/Continents/";
    QDir d(path);

    QStringList l = d.entryList(QStringList() << "*.cfg", QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);

    for(int i = 0; i < l.size(); ++i)
    {
        QFile file(path + l[i]);
        QString name = l[i].left(l[i].size() - 4);

        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qDebug() << "Error : continents config file \"" << path + l[i] << "\" is missing.";
        }
        QTextStream out(&file);
        out >> m_table[name].lands >> m_table[name].bonus;
    }
}

bool Continents::isFull(const QString& n, const QList<State*>& l) const
{
    if(!m_table.contains(n))
    {
        return false;
    }

    size_t num = 0;
    for(int i = 0; i < l.size(); ++i)
    {
        if(l[i]->continent() == n)
            ++num;
    }

    if(num >= m_table.value(n).lands)
        return true;

    return false;
}

QStringList Continents::fullList(const QList<State*>& l) const
{
    QStringList r;
    QMap<QString, Continent>::const_iterator i = m_table.constBegin();
    while (i != m_table.constEnd())
    {
        if(isFull(i.key(), l))
        {
            r.append(i.key());
        }
        ++i;
    }
    return r;
}

size_t Continents::reinforcementBonus(const QString& n) const
{
    if(!m_table.contains(n))
        return 0;

    return m_table.value(n).bonus;
}
size_t Continents::totalReinforcementBonus(const QList<State*>& l) const
{
    QStringList r = fullList(l);
    size_t n = 0;

    for(int i = 0; i < r.size(); ++i)
        n += reinforcementBonus(r[i]);

    return n;
}
